package my.graduation.controller.common;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import my.graduation.config.AlipayConfig;
import my.graduation.constant.ExamRecordStatusConstant;
import my.graduation.constant.RegRecordStatusConstant;
import my.graduation.dto.PayDto;
import my.graduation.entity.Record;
import my.graduation.entity.RegistrationRecord;
import my.graduation.result.Result;
import my.graduation.service.ExaminationRecordService;
import my.graduation.service.RegistrationRecordService;
import my.graduation.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: RavenLyn
 * @Date: 2024-12-19
 */
@RequestMapping("/alipay")
@RestController
public class AlipayController {
    @Autowired
    private AlipayConfig alipayTemplate;

    @Autowired
    private RegistrationRecordService registrationRecordService;

    @Autowired
    private ExaminationRecordService examinationRecordService;

//    @Autowired
//    private WebSocketServer webSocketServer;


    /**
     * 支付接口
     */
    @PostMapping(value = "/pay", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String,Object> pay(@RequestBody PayDto dto) throws AlipayApiException {
        Record record = new Record();
        BeanUtils.copyProperties(dto,record);
        System.out.println("dto.getExamRecordId");
        System.out.println(dto.getExamRecordId());
        return alipayTemplate.pay(record);
    }

    /**
     * 异步回调
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
//            String businessType = params.get("business_type");
            // 支付宝验签
            if (AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipayPublicKey(), "UTF-8",alipayTemplate.getSignType())) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + alipayTradeNo);
                System.out.println("商户订单号: " + tradeNo);
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + gmtPayment);
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(gmtPayment); // 使用 try-catch 捕获 ParseException
//                System.out.println("businessType:"+businessType);
                if("挂号预约支付".equals(params.get("subject"))){
                    // 更新订单状态 status=1 把 tradeNo set进去 gmtPayment
                    Boolean i = registrationRecordService.paySuccess(Integer.valueOf(tradeNo), RegRecordStatusConstant.PAID,new Timestamp(date.getTime()));
                    if(i){
                        System.out.println("挂号订单已支付！");
                    }else {
                        System.out.println("挂号订单支付失败！");
                        return "failure";
                    }
                }else {
                    // 更新订单状态 status=1 把 tradeNo set进去 gmtPayment
                    Boolean i = examinationRecordService.paySuccess(Integer.valueOf(tradeNo), ExamRecordStatusConstant.PAID,new Timestamp(date.getTime()));
                    if(i){
                        System.out.println("检查订单已支付！");
                    }else {
                        System.out.println("检查订单支付失败！");
                        return "failure";
                    }
                }
            }
        }
        return "success";
    }

    /**
     * 同步回调
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/return_data")
    public String payReturn(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        boolean check = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipayPublicKey(), "UTF-8", alipayTemplate.getSignType());

        if(check){
            return "<html>\n" +
                    "<body>\n" +
                    "<h1>支付成功！</h1>\n" +
                    "<p>您的订单已成功支付。</p>\n" +
                    "<script>\n" +
                    "    // 设置5秒后执行的函数\n" +
                    "    setTimeout(function() {\n" +
                    "        // 关闭当前窗口\n" +
                    "        window.close();\n" +
                    "    }, 5000); // 5000毫秒等于5秒\n" +
                    "</script>\n" +
                    "</body>\n" +
                    "</html>";
        }else {
            return "failure";
        }
    }

    /**
     * 取消预约-退款
     * @param dto
     * @return
     */
    @PostMapping(value = "/refund", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String payRefund(@RequestBody PayDto dto) throws Exception {
        Record record = new Record();
        BeanUtils.copyProperties(dto,record);
        return alipayTemplate.refund(record);
    }
}
